package com.example.demo.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.InputSource;

public class MessageUtil {  
	  
    /** 
     * 解析微信发来的请求（XML） 
     *  
     * @param request 
     * @return 
     * @throws Exception 
     */  
    public static Map<String, String> request2Map(HttpServletRequest request) throws Exception {  
        // 将解析结果存储在HashMap中  
        Map<String, String> map = new HashMap<String, String>();  
  
        // 从request中取得输入流  
        InputStream inputStream = request.getInputStream();
        System.out.println(inputStream);
        // 读取输入流  
        SAXReader reader = new SAXReader();  
        try {
        	Document document = reader.read(inputStream);  
            // 得到xml根元素  
            Element root = document.getRootElement();  
            // 得到根元素的所有子节点  
              
            @SuppressWarnings("unchecked")  
            List<Element> elementList = root.elements();  
      
            // 遍历所有子节点  
            for (Element e : elementList)  
                map.put(e.getName(), e.getText());  
      
            // 释放资源  
            inputStream.close();  
            inputStream = null; 
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return map;
		}
        return map;  
    }  
    
	/**
	 * 将request中的消息提取出来，返回String结果
	 * @param request
	 * @return
	 */
	public static String request2xml(HttpServletRequest request) {
		InputStream inputStream;
		StringBuffer sb = new StringBuffer();
		try {
			inputStream = request.getInputStream();
			String s;
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			while ((s = in.readLine()) != null) {
				sb.append(s);
			}
			in.close();
			inputStream.close();
			return sb.toString();
		} catch (Exception e) {
			return e.getMessage();
		}
	}
	
	/**
	 * 将xml String进行格式化输出，返回String结果
	 * @param str
	 * @return
	 * @throws Exception
	 */
	public static String formatXml(String str) throws Exception {
		Document document = null;
		document = DocumentHelper.parseText(str);
		// 格式化输出格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("gb2312");
		StringWriter writer = new StringWriter();
		// 格式化输出流
		XMLWriter xmlWriter = new XMLWriter(writer, format);
		// 将document写入到输出流
		xmlWriter.write(document);
		xmlWriter.close();
		return writer.toString();
	}
	
	/**
	 * 将xml String转为Map，以Map返回
	 * @param xml
	 * @return
	 * @throws Exception
	 */
	public static Map<String, String> xmlToMap(String xml) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		InputSource in = new InputSource(new StringReader(xml));
		in.setEncoding("UTF-8");
		SAXReader reader = new SAXReader();
		Document document = reader.read(in);
		Element root = document.getRootElement();
		List<Element> elements = root.elements();
		for (Iterator<Element> it = elements.iterator(); it.hasNext();) {
			Element element = it.next();
			map.put(element.getName(), element.getTextTrim());
		}
		return map;
	}
}